# -*- coding: utf-8 -*-
__author__ = 'yykrlc'
# 简单增删改查公共接口
import re, datetime
from sqlalchemy.inspection import inspect
from app import db, app_
api_log = app_.logger

def com_obj_dict(objs):
    data = []
    if len(objs) > 0:
        count = len(objs)
        for obj in objs:
            obj = convert_to_dict(obj)
            data.append(obj)
    else:
        count = 0
    return data, count

def first_item(data):
    """获取列表第一项"""
    if len(data) > 0:
        return data[0]
    return {}


def get_pk(record):
    """获取主键"""
    return inspect(record.__class__).primary_key[0].name


def convert_to_dict(obj):
    """把Object对象转换成Dict对象"""
    if obj is None:
        return {}
    dict_ = {}
    dict_.update(obj.__dict__)
    try:
        dict_.__delitem__("_sa_instance_state")
    except:
        pass
    # for i in dir(obj):  # 把自定义图片地址加入字典
    #     if i.endswith("_path"):
    #         dict_.update({i: eval("obj.%s" % i)})
    for j in dict_:
        if dict_[j] in ["None", None]:
            dict_[j] = ""
    return dict_


def obj_to_dict(data_list):
    """将model-list 对象转换为字典"""
    data = []
    for c in data_list:
        data.append(convert_to_dict(c))
    return data


def set_data_to_record(record, data):
    """ 赋值给models对象，model的增，改函数调用"""

    def _filter_build_in(keys):
        new_keys = list()
        for k in keys:
            if not k.startswith("_"):
                new_keys.append(k)
        return new_keys

    attrs = _filter_build_in(dir(record))

    """将data设置值到record对象中"""
    for key in attrs:
        if data.has_key(key):
            setattr(record, key, data[key])


def check_record_exists(record, keys_query_cond):
    """
    根据keys检查数据记录是否已经存在
    :param record:
    :param keys_query_cond:
    :return:
    """
    rv = db.session.query(record.__class__).filter_by(**keys_query_cond).all()
    if len(rv) > 0:
        return getattr(rv[0], get_pk(record))
    else:
        return False


def update_data(record, attrs, passwd=None):
    """
    更新记录的attrs字段，不允许为空
    :param record:
    :param attrs: 字段名的 list， 如["product_count","product_name"]
    :return:
    例：
    data = {"passwd": ranint_passwd, "id": user_one["id"]}
    attr = ["passwd"]
    """
    record_id = getattr(record, get_pk(record))  # 获取主键
    if int(record_id) > 0:
        if len(attrs) == 0:
            api_log.error( "update operation should specify column names: " + str(record.__class__) + "  id: " + str(record_id))
            return
        update_columns = {}
        for a in attrs:
            # 处理更新密码
            # if a == "passwd": # passwd reset
            #     recod = db.session.query(record.__class__).filter_by(**{get_pk(record): record_id}).first()
            #     if recod:
            #         recod.passwd = passwd
            #         db.session.add(recod)
            #         db.session.commit()
            # else:
            update_columns[a] = getattr(record, a)
        if update_columns:
            db.session.query(record.__class__).filter_by(**{get_pk(record): record_id}).update(update_columns)
            db.session.commit()
        return record_id
    else:
        return False


def update_where(record, item_list, where_str):
    """
    更新记录的item_list字段，不允许为空
    :param record:
    :param item_list: 需要更新的字段list， 如["product_count","product_name"]
    :param where_str: 查询条件， 如{'id': 1}
    :return:
        def update_notification(data, item_list, where_str):
        record = AccountNotification()
        set_data_to_record(record, data)
        return update_where(record, item_list, where_str)
    """
    record_id = getattr(record, get_pk(record))
    if len(item_list) == 0:
        return
    update_columns = {}
    for key in item_list:
        update_columns[key] = getattr(record, key)
    if update_columns:
        if not where_str:
            where_str = {get_pk(record): record_id}
        db.session.query(record.__class__).filter_by(**where_str).update(update_columns)
        db.session.commit()
    return record_id


# 增
def save_data(table, data):
    """
    插入记录，并返回id
    例：
    table = EduUserProfile
    data = {"user_id": user["id"]}
    """
    record = table()
    set_data_to_record(record, data)
    db.session.add(record)
    db.session.commit()
    record_id = getattr(record, get_pk(record))
    # flog.info("insert a record --" + str(record) + "id--: " + str(record_id))
    return record_id


# 删
def delete_data(table, query_condition):
    """
    删除符合条件的整条数据
    例：
    table = EduUserProfile
    query_condition = {"user_id": user["id"]}
    """
    x = table.query.filter_by(**query_condition).delete(synchronize_session=False)
    # db.session.delete(table.query.filter_by(**query_condition))
    db.session.commit()
    return x


# 　改
def reset_data_attr(table, data, attr):
    """
    例：
    table = EduUserProfile
    data = {"user_id": user["id"],"user_name":100,"org_id":200}
    attr = ["user_name","org_id"]
    """
    record = table()
    set_data_to_record(record, data)
    try:
        passwd = data["passwd"]
    except:
        passwd = None
    return update_data(record=record, attrs=attr, passwd=passwd)


# 查

def get_table_data_first(table, query_condition, dict_status=True):
    """
    例：
    table = EduUserProfile
    query_condition = {"user_id": user["id"]}
    dict_status：True 返回字典，False 返回model对象
    """

    data_ = table.query.filter_by(**query_condition).first()
    if dict_status:
        data = convert_to_dict(data_)
    else:
        data = data_

    return data


def get_table_data(table, query_condition, order_by=None, _order_by=None, dict_status=True):
    """
    例：.order_by(User.id)
    table = EduUserProfile
    query_condition = {"user_id": user["id"]}
    """
    # data_list = table.query.filter_by(**query_condition).all()
    # print "===query_condition==="
    # print query_condition
    if order_by:
        data_list = table.query.filter_by(**query_condition).order_by(order_by).all()  # .limit(1000)
    elif _order_by:
        data_list = table.query.filter_by(**query_condition).order_by(db.desc(_order_by)).all()  # .limit(1000)
    elif "created_time" in dir(table):
        data_list = table.query.filter_by(**query_condition).order_by(db.desc(table.created_time)).all()
    else:
        data_list = table.query.filter_by(**query_condition).all()
    if dict_status:
        data = obj_to_dict(data_list)
    else:
        data = data_list
    return data


def get_table_data_page(table, query_condition, order_by=None, _order_by=None, page=1, per_page=10):
    """
    例：.order_by(User.id)
    table = EduUserProfile
    query_condition = {"user_id": user["id"]}
    """
    # data_list = table.query.filter_by(**query_condition).all()
    if order_by:
        data_list = table.query.filter_by(**query_condition).order_by(order_by)  # .limit(1000)
    elif _order_by:
        data_list = table.query.filter_by(**query_condition).order_by(db.desc(_order_by)) # .limit(1000)
    elif "created_time" in dir(table):
        data_list = table.query.filter_by(**query_condition).order_by(db.desc(table.created_time))
    else:
        data_list = table.query.filter_by(**query_condition)
    pagination = data_list.paginate(page, per_page,error_out=False)
    # posts = pagination.items

    return pagination
